<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;

class UserController extends Controller {

    public function login(Request $request) {

        if (session()->has('wechat_user')) {
            return redirect('/');
        }
        $options = [
            'debug'  => env('WX_DEBUG'),
            'app_id' => env('WX_APP_ID'),
            'secret' => env('WX_SECRET'),
            'token'  => env('WX_TOKEN'),
            'oauth'  => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/login',
            ]
        ];
        $app     = new Application($options);
        $oauth   = $app->oauth;
        $user    = $app->oauth->user();
        session(['wechat_user' => $user]);
        $targetUrl = session()->has('target_url') ? '/' : session(['target_url']);

        header('location:' . $targetUrl);
    }

    public function index(Request $request) {
        $options = [
            'debug'  => env('WX_DEBUG'),
            'app_id' => env('WX_APP_ID'),
            'secret' => env('WX_SECRET'),
            'token'  => env('WX_TOKEN'),
            'oauth'  => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/login',
            ]
        ];
        $app     = new Application($options);
        $oauth   = $app->oauth;

        if (!session()->has('wechat_user')) {

            session(['target_url' => '/']);
            return $oauth->redirect();
        }

        #dd(session('wechat_user'));
        $wechat_user = session('wechat_user');

        echo $wechat_user->id;
        echo '<hr>';
        echo $wechat_user->nickname;
        echo '<hr>';
        echo $wechat_user->token;
        echo '<hr>';
        echo '<img src="'.$wechat_user->avatar.'" />';

    }
}
